package com.hulk.dryad.manage.framework.websocket.server.handshake;

import cn.hutool.core.util.StrUtil;
import com.hulk.dryad.common.constant.CommonConstants;
import com.hulk.dryad.common.util.SecurityUtils;
import com.hulk.dryad.manage.framework.datasource.DynamicDataSourceHolder;
import com.hulk.dryad.manage.framework.tenant.TenantContextHolder;
import com.hulk.dryad.manage.framework.websocket.common.principal.WsPrincipal;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServletServerHttpRequest;
import org.springframework.lang.Nullable;
import org.springframework.security.core.userdetails.User;

import javax.servlet.http.HttpServletRequest;
import java.security.Principal;


/**
 * 默认的 Principal 解析
 *
 * @author
 */
@Slf4j
@RequiredArgsConstructor
public class DefaultWebSocketPrincipalResolve implements WebSocketPrincipalResolve {


	private static final  String nameTenant = CommonConstants.TENANT_ID;


	@Nullable
	@Override
	public Principal resolve(ServerHttpRequest request) {
		HttpServletRequest  httpServletRequest = ((ServletServerHttpRequest)request).getServletRequest();

		String tenant = httpServletRequest.getParameter(nameTenant);
		if(StrUtil.isBlank(tenant) ){
			return null;
		}
		User user = SecurityUtils.getUser();
		if (user != null) {
			setTenantContext(tenant);
			return new WsPrincipal(user.getUsername(),tenant);
		}
		return null;
	}

	/**
	 * 设置租户上下文,可用于选择数据源
	 */
	private void setTenantContext(String tenant) {
		DynamicDataSourceHolder.set(tenant);

	}


}





